package net.tngou.http;



import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;

import net.tngou.cache.CacheEngine;
import net.tngou.cache.EhCacheEngine;
import net.tngou.cache.J2CacheEngine;
import net.tngou.pojo.POJO;
import net.tngou.pojo.User;
import net.tngou.util.OAuthUtil;
import net.tngou.util.StringUtil;

import org.apache.commons.lang3.time.DateUtils;





/**
 * 这里我们主要用的的ehcache来代替传统的session
 * @author 陈磊
 *
 */

public class SessionContext  implements net.tngou.http.HttpSession {

	
	private static CacheEngine cacheEngine =new  J2CacheEngine().getInstance();
	private final String fullyQualifiedName = "session";
	@Override
	public void setAttribute(String name, Object value)
	{
		
		cacheEngine.add(fullyQualifiedName, name, value);
	}

	@Override
	public void removeAttribute(String name)
	{
		cacheEngine.remove(fullyQualifiedName, name);
	}

	@Override
	public Object getAttribute(String name)
	{
		return cacheEngine.get(fullyQualifiedName, name);
	}

	@Override
	public User getUser(String userid) {
		
		if(StringUtil.isBlank(userid))return null;
		
		User user = (User) getAttribute(userid);  //缓存里面取得user
//		if(user==null) //如果session缓存里面没有，
//		{
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("access_token", userid);
//			Login bean = new Login();
//			Login login = bean.get(map );
//			if(login!=null)
//			{
//				user=new User().get(login.getUser());			
//				int isauto = login.getIsauto();
//				Timestamp timestamp=new  Timestamp(DateUtils.addHours(new Date(), 1).getTime());
//				if(isauto==1)timestamp=new  Timestamp(DateUtils.addDays(new Date(), 30).getTime());
//				map.clear();
//				map.put("expiredtime", timestamp);
//				bean.update(map, login.getId());
//				setUser(user);//设置	
//				
//			}
//		}
		
		return user;
	}

	@Override
	public void setUser(User user) 
	{
		String yybid=OAuthUtil.Access_token(user.getUsername(),user.getPassword());
		setAttribute(yybid, user);
		
	}

	@Override
	public void deleteUser(String userid) {
		removeAttribute(userid);
		
	}


	
	

}
